import { baseUrl } from "@/assets/config";


uni.addInterceptor('request', {
  invoke(args) {
    // request 触发前拼接 url
    args.url = `${baseUrl}${args.url}`
    if (!args.header) {
      args.header = {};
    }

    const userStore = useUserStore();
    args.header['Authorization'] = userStore.token // 让每个请求携带自定义token 请根据实际情况自行修改
  }
})
const request = (options: RequestOptions): Promise<any> => {
  return new Promise((resolve, reject) => {

    const config = {
      ...options,
      success: (res) => {

        // 未设置状态码则默认成功状态
        const code = res.data.code || res.statusCode || 200;

        // 获取错误信息
        const msg = errorCode[code] || res.data.msg || errorCode['default']

        if (res.statusCode == 500) {
          uni.showToast({
            icon: 'error',
            title: '链接失败，请检查网络!',
            duration: 2000
          });
          reject(msg)
        } else if (code == 401) {
          if (options.url != '/getInfo') {
            uni.showModal({
              title: '系统提示',
              content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
              success: function (res) {
                if (res.confirm) {
                  handerLogin();
                }
              }
            });
          }
          reject('无效的会话，或者会话已过期，请重新登录。')
        } else if (code == 404) {
          uni.showToast({
            icon: 'error',
            title: msg,
            duration: 2000
          });
          reject(msg);
        } else if (code == 500) {
          uni.showToast({
            icon: 'error',
            title: msg,
            duration: 2000
          });
          reject(msg);
        } else if (code != 200) {
          uni.showToast({
            icon: 'error',
            title: msg,
            duration: 2000
          });
          reject(msg);
        } else {
          resolve(res.data);
        }

      },
      fail: (err) => {
        uni.showToast({
          icon: 'error',
          title: `${err.errno} -- ${err.errMsg}`,
          duration: 2000
        });
        reject(err)
      }
    }

    uni.request(config);
  })
}

export { request }